package com.i2works.smartluolong.utils.shiro;

import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.session.ExpiredSessionException;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.DefaultSessionKey;
import org.apache.shiro.session.mgt.SessionKey;
import org.apache.shiro.session.mgt.SimpleSession;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.session.mgt.WebSessionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Collection;

/**
 * 自定义会话管理器
 *
 * @author Liu Yutao koal@vip.qq.com
 * @date 2017/5/25 19:34
 */
public class SimpleWebSessionManager extends DefaultWebSessionManager implements WebSessionManager {

    @Autowired
    private CacheManager cacheManager;

    private final Logger logger = LoggerFactory.getLogger(getClass());

    public SimpleWebSessionManager() {
        super();
    }

    @Override
    public void validateSessions() {
        if (logger.isInfoEnabled()) {
            logger.error("验证所有活动会话...");
        }
        int invalidCount = 0;
        Collection<?> activeSessions = getActiveSessions();
        if (activeSessions != null && !activeSessions.isEmpty()) {
            for (Object activeSession : activeSessions) {
                Session session = (Session) activeSession;
                try {
                    SessionKey key = new DefaultSessionKey(session.getId());
                    validate(session, key);
                } catch (InvalidSessionException e) {
                    if (cacheManager != null) {
                        SimpleSession s = (SimpleSession) session;
                        if (s.getAttribute("user") != null) {
                            cacheManager.getCache(null).remove(s.getAttribute("user"));
                        }
                    }
                    if (logger.isDebugEnabled()) {
                        boolean expired = e instanceof ExpiredSessionException;
                        String msg = (new StringBuilder()).append("失效会话ID [").append(session.getId()).append("]").append(expired ? " (失效)" : " (停止)").toString();
                        logger.error(msg);
                    }
                    invalidCount++;
                }
            }

        }
        if (logger.isInfoEnabled()) {
            String msg = "会话验证结束！";
            if (invalidCount > 0) {
                msg = (new StringBuilder()).append(msg).append("[").append(invalidCount).append("]会话停止。").toString();
            } else {
                msg = (new StringBuilder()).append(msg).append("没有需要停止的会话。").toString();
            }
            logger.error(msg);
        }
    }

    @Override
    public void setCacheManager(CacheManager cacheManager) {
        this.cacheManager = cacheManager;
    }

}
